#include<opencv2/opencv.hpp>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>

cv::Rect adjustFitScreenFrame(cv::Rect &frame, cv::Rect &superFrame)
{
    if (superFrame.width == 0 || superFrame.height == 0) {
        return cv::Rect();
    }
    float wScale = frame.width * 1.0/superFrame.width;
    float hScale = frame.height * 1.0/superFrame.height;
    if (wScale > hScale)
    {
        float width = superFrame.width;
        float height = superFrame.width * 1.0/frame.width*frame.height;
        return cv::Rect(0, -(height-superFrame.height)/2.0, width, height);
    }else if(wScale < hScale)
    {
        float width = superFrame.height * 1.0/frame.height*frame.width;
        float height = superFrame.height;
        return cv::Rect(-(width-superFrame.width)/2.0, 0, width, height);
    }
    superFrame.x = 0;
    superFrame.y = 0;
    return superFrame;
}

cv::Mat imgFitScale(cv::Mat &img, cv::Rect &superFrame){
    cv::Mat allImg = cv::Mat::zeros(superFrame.width, superFrame.height, CV_8UC3);
    cv::Rect rect(0, 0, img.cols, img.rows);
    cv::Rect scaleRect = adjustFitScreenFrame(rect, superFrame);
    cv::Mat scaleImg;
    cv::resize(img, scaleImg, cv::Size(scaleRect.width, scaleRect.height), 0, 0, cv::INTER_CUBIC);
    cv::Mat img1 = allImg(scaleRect);
    scaleImg.copyTo(img1);
    return allImg;
}

void cameraCapture(){
    cv::VideoCapture cameraCapture(0);
    cv::VideoWriter outputVideo;

    int w = (int)cameraCapture.get(cv::CAP_PROP_FRAME_WIDTH);
    int h = (int)cameraCapture.get(cv::CAP_PROP_FRAME_HEIGHT);
    int frameRate = cameraCapture.get(cv::CAP_PROP_FPS);
    int frameCount{};
    outputVideo.open("./test.mp4", cv::VideoWriter::fourcc('a', 'v', 'c', '1'), 15, cv::Size(w, h));

    cv::Mat img;
    cv::namedWindow("pic", cv::WINDOW_AUTOSIZE);
    while (cameraCapture.isOpened()){
        cameraCapture >> img;
        outputVideo.write(img);
        cv::imshow("pic", img);
        frameCount++;
        if (cv::waitKey(40) == 27 || frameCount == 250)// 空格暂停
        {
            break;
        }
    }
    outputVideo.release();
}

int main() {

    cameraCapture();

    cv::waitKey();
    return 0;
}
